import { DefaultHistoryInfo, IHistoryInfo } from "@/model/HistoryInfo";
import { GameType } from "@/model/GameType";
import { IHistory } from "@/model/History";

export class HistoryInfos {
  private readonly historyInfos: IHistoryInfo[];
  private static instance: HistoryInfos;

  private constructor() {
    this.historyInfos = [];
  }

  get Length() {
    return this.historyInfos.length;
  }

  /**
   * 创建一局游戏历史记录
   * @param t 游戏类型
   * @return {string} 记录的ID
   */
  public Create(t = GameType.NumGuess): string {
    const historyInfo = new DefaultHistoryInfo();
    historyInfo.Type = t;
    this.historyInfos.push(historyInfo);
    return this.historyInfos[this.Length - 1].ID!;
  }

  /**
   * 更新记录
   * @param id
   * @param histories
   * @constructor
   */
  public Update(id: string, histories: IHistory[]): string | null {
    // 找到 ID一样的
    const find = this.historyInfos.find(historyInfo => historyInfo.ID === id);
    if (!find) {
      return "没有找到数据";
    }

    find.CrateTime = new Date();
    find.Histories = histories;
    return null;
  }

  public ReadAll(): IHistoryInfo[] {
    return this.historyInfos;
  }

  public Read(id: string): IHistoryInfo | undefined {
    return this.historyInfos.find(historyInfo => historyInfo.ID === id);
  }

  public static Instance() {
    if (!HistoryInfos.instance) {
      HistoryInfos.instance = new HistoryInfos();
    }
    return HistoryInfos.instance;
  }
}
